/* Training file to see how the MPI_Send and MPI_Recv function worked*/

#include <stdio.h>
#include <mpi.h>
#define send_data_tag 2001
#define return_data_tag 2002


main(int argc, char **argv) 
{
   int array[10];
   int i, a, sum;
   int my_id, root_process, ierr, num_procs;
   MPI_Status status;
   
   
   

   /* Now replicate this process to create parallel processes.  */
   ierr = MPI_Init(&argc, &argv);
   
   
   a = 0;
   root_process = 0;
   
   printf("CHECK!\n");

   /* find out MY process ID, and how many processes were started */
   ierr = MPI_Comm_rank(MPI_COMM_WORLD, &my_id);
   ierr = MPI_Comm_size(MPI_COMM_WORLD, &num_procs);

   if(my_id == root_process)
   {
      for (i=0;i<10;i++)
      {
         array[i] = i;
      
      }
          
      
      for (i=1;i<num_procs;i++)
      {
         a = 10;
         
         ierr = MPI_Send( &a, 1, MPI_INT,
            i, send_data_tag, MPI_COMM_WORLD);
            
         ierr = MPI_Send(&array[0], 10, MPI_INT,
            i, send_data_tag, MPI_COMM_WORLD);
         
      }
      
      sum = 0;
      for (i=1;i<num_procs;i++)
      {
         
         ierr = MPI_Recv( &a, 1, MPI_INT,
            i, return_data_tag, MPI_COMM_WORLD, &status);
         
         sum += a;
      }
      
      printf("Final sum is : %i \n",sum);
      
   }

   else
   {
      /* I must be slave process, so I must receive my array segment,*/
      ierr = MPI_Recv( &a, 1, MPI_INT,
            root_process, send_data_tag, MPI_COMM_WORLD, &status);
      
      ierr = MPI_Recv( &array, 10, MPI_INT,
            root_process, send_data_tag, MPI_COMM_WORLD, &status);
      
      printf("process %i of %i, received %i\n",my_id,num_procs,a);
      
      sum = 0;
      for (i=0;i<a;i++)
      {
         sum += array[i]+my_id;
      }
      
      printf("%i Sending sum of %i \n",my_id,sum);
      
      ierr = MPI_Send( &sum, 1, MPI_INT,
            root_process, return_data_tag, MPI_COMM_WORLD);
      

   }

   /* Stop this process */

   ierr = MPI_Finalize();
}














   

